package jp.bgbt.fles.app.bluetooth;

import com.common.utils.LogUtil;
import com.common.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import jp.bgbt.fles.app.bean.EventMsg;

public class BleCommandUtil {

    private static BleCommandUtil instance = new BleCommandUtil();
    private List<CommandBean> commandList = new ArrayList<>();
    private int sendedCommandIndex;
    private Disposable commonDisposable;
    private Disposable baseInfoDisposable;
    private Disposable readEleDisposable;

    //    public static String qudong = "0x120x0e0x000x070x000x000x000x000x000x000x000x000x000x000x000x000x00" +
//        "0x130x0e0xa30x070x000x000x000x000x000x000x000x000x000x000x000x000x00" +
//        "0x140x0e0xa30x070x000x000x000x000x000x000x000x000x000x000x000x000x00" +
//        "0x110x0e0x000x070x000x000x000x000x000x000x000x000x000x000x000x000x00";
//    public static String qudong = "0x130x0e0x7f0x0A0x000x000x000x000x000x000x000x000x000x000x000x000x00" +
//        "0x140x0e0x550x0A0x000x000x000x000x000x000x000x000x000x000x000x000x00" +
//        "0x110x0e0x000x0A0x000x000x000x000x000x000x000x000x000x000x000x000x00";
    public static String qudong = "0x120x0e0x000x010x000x010x890x010x000x010x890x010x890x010x000x010x00" +
            "0x130x0e0xa30x010x000x010x000x010xa30x010xa30x010x000x010xa30x010x00" +
            "0x140x0e0x000x010x000x010x000x010x000x010x000x010x000x010x000x010x00" +
            "0x110x0e0x000x010xb70x010x000x010xb70x010x000x010xb70x010x000x010x00";

    public ArrayList<byte[]> getQudong(String quDong, int length) {
        quDong = quDong.toLowerCase();
        ArrayList<byte[]> list = new ArrayList<byte[]>();
        String[] stringQD = new String[length];
        for (int i = 0; i < stringQD.length; i++) {
            stringQD[i] = quDong.substring(68 * i, 68 * (i + 1));
        }
        byte[] a;
        for (int i = 0; i < stringQD.length; i++) {
            a = new byte[20];
            a[0] = (byte) 234;
            a[1] = (byte) 2;
            a[19] = (byte) 174;
            String[] stringoneQD = stringQD[i].split("0x");
            for (int j = 1; j < stringoneQD.length; j++) {
                int k = Integer.valueOf(stringoneQD[j], 16).intValue();

                a[j + 1] = (byte) k;
            }
            list.add(a);
        }
        list.add(BleConstant.writeServiceByte);
        return list;
    }


    public static BleCommandUtil getInstance() {
        return instance;
    }

    public void sendReadDeviceInfoData() {
        commandList = new ArrayList<>();
        if (baseInfoDisposable != null && !baseInfoDisposable.isDisposed()) {
            baseInfoDisposable.dispose();
        }
        Observable observable = Observable.interval(0, 10, TimeUnit.MILLISECONDS)
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io());
        BleDeviceInfo.getInstance().setCanSendNextCommand(true);
        observable.subscribe(new Observer() {
            int count = 0;

            @Override
            public void onSubscribe(Disposable d) {
                baseInfoDisposable = d;
            }

            @Override
            public void onNext(Object o) {
                if (!BleDeviceInfo.getInstance().isDeviceConnected())
                    baseInfoDisposable.dispose();
                if (BleDeviceInfo.getInstance().isCanSendNextCommand()) {
                    count = 0;
                    if (!readBaseData()) {
                        baseInfoDisposable.dispose();
                    }
                } else {
                    if (count % 200 == 0) {
                        if (!readBaseData()) {
                            baseInfoDisposable.dispose();
                        }
                    }
                }
                count++;
                if (count == 1500) {
                    //4.7日修改 原来为800
                    LogUtil.d("@@@@@@@@@@@@@@@@@@@读基本信息超过8秒，失败！！");
                    if(StringUtils.isEmpty(BleDeviceInfo.getInstance().getDeviceRandom())) {
                        EventBus.getDefault().post(new EventMsg(EventMsg.MSG_READ_RANDOM_FAILED));
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private boolean readBaseData() {
        boolean flag = true;
        if (StringUtils.isEmpty(BleDeviceInfo.getInstance().getDeviceRandom())) {
            sendBleCommandData(BleConstant.readRandom);
        } else if (StringUtils.isEmpty(BleDeviceInfo.getInstance().getDeviceVersion())) {
            sendBleCommandData(BleConstant.readVersionByte);
        } else {
            flag = false;
        }
        if (flag)
            BleDeviceInfo.getInstance().setCanSendNextCommand(false);
        return flag;
    }

    private void sendBleCommandData(byte[] data) {
        if (!BleDeviceInfo.getInstance().isDeviceConnected()) {
            LogUtil.e("设备断开连接，停止发送指令");
            commandList.clear();
            return;
        }
        BleService service = BleServiceManager.getInstance().getBluetoothService();
        if (service != null) {
            service.writeLlsAlertLevel(BleConstant.SERVICE_UUID1, BleConstant.CHA_UUID1, data);
        }
    }

    public void sendCommandList(List<byte[]> list) {
        for (byte[] b : list) {
            CommandBean bean = new CommandBean();
            bean.setCommandData(b);
            commandList.add(bean);
        }
        startSendCommand();
    }

    public void sendCommand(byte[] data) {
        CommandBean bean = new CommandBean();
        bean.setCommandData(data);
        commandList.add(bean);
        if (data[2] == (byte) 0xD8) {
            LogUtil.e("开始读wifi的mac地址，指令已添加到集合，集合大小为" + commandList.size() + ",已发送到第" + sendedCommandIndex + "条");
        }
        startSendCommand();
    }

    private void startSendCommand() {
        if (commonDisposable != null && !commonDisposable.isDisposed())
            commonDisposable.dispose();
        List<CommandBean> list = new ArrayList<>();
        for (CommandBean b : commandList) {
            if (b.isHasRecvResponse() || b.getSendedCount() > 4) {
                list.add(b);
                if (b.getCommandData()[2] == (byte) 0xD8) {
                    LogUtil.e("读取wifi的mac地址指令即将删除");
                }
            }
        }
        boolean removeOk = commandList.removeAll(list);
//        LogUtil.e("删除已处理指令是否成功? " + removeOk);
//        for (CommandBean commandBean : list) {
//            LogUtil.e("移除已处理的指令，" + commandBean.getCommandData()[2] + " , " + commandBean.getCommandData()[3]);
//        }
        sendedCommandIndex = 0;
        Observable.interval(50, 20, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Observer<Long>() {
                    int count = 0;

                    @Override
                    public void onSubscribe(Disposable d) {
                        commonDisposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (sendedCommandIndex < commandList.size()) {
                            CommandBean commandBean = commandList.get(sendedCommandIndex);
                            if (commandBean.getSendedCount() > 4) {
                                LogUtil.d("第" + sendedCommandIndex + "条指令已发送超过5次，继续下一条");
                                sendedCommandIndex++;
                                count = 0;
                            } else {
                                if (commandBean.isHasRecvResponse()) {
                                    LogUtil.d("第" + sendedCommandIndex + "条指令已收到回复，发送下一条");
                                    sendedCommandIndex++;
                                    count = 0;
                                } else {
                                    if (count % 100 == 0) {
                                        if (!commandBean.isHasRecvResponse()) {
                                            sendBleCommandData(commandBean.getCommandData());
                                            commandBean.setSendedCount(commandBean.getSendedCount() + 1);
                                        }
                                    } else {

                                    }
                                    count++;
                                }
                            }
                        } else {
                            commonDisposable.dispose();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        LogUtil.d("指令发送完毕,总共" + commandList.size() + "条，sendIndex = " + sendedCommandIndex);
                        sendedCommandIndex = 0;
                        commandList.clear();
                    }
                });
    }

    public void readEle() {
        sendCommand(BleConstant.readElePressure);
    }

    public void readEleDelay() {
        if (readEleDisposable != null)
            readEleDisposable.dispose();
        Observable.just(0).delay(3, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        readEleDisposable = d;
                    }

                    @Override
                    public void onNext(Integer integer) {
                        readEle();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void setCommandResponseReceived2(byte[] data) {
        if (sendedCommandIndex < commandList.size()) {
            CommandBean bean = commandList.get(sendedCommandIndex);
            if (!bean.isHasRecvResponse() && data[1] == bean.getCommandData()[2]) {
                bean.setHasRecvResponse(true);
                return;
            }
        }
    }

    public void setCommandResponseReceived1(byte[] data) {
        if (sendedCommandIndex < commandList.size()) {
            CommandBean bean = commandList.get(sendedCommandIndex);
            String timeValue = String.format("%02X ", data[1]).toString().trim();
            if (!bean.isHasRecvResponse() && data[1] == bean.getCommandData()[1]) {
                bean.setHasRecvResponse(true);
            }
        }
    }


}
